using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WPF_MVVM_Test.MVVM_Model.Material;

namespace WPF_MVVM_Test.MVVM_View.Material
{
    /// <summary>
    /// SimpleTreeComboBox.xaml 的交互逻辑
    /// </summary>
    public partial class SimpleTreeComboBox : System.Windows.Controls.UserControl
    {
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<MaterialCategory>), 
                typeof(SimpleTreeComboBox), new PropertyMetadata(null, OnItemsSourceChanged));

        public static readonly DependencyProperty SelectedValueProperty =
            DependencyProperty.Register("SelectedValue", typeof(string), 
                typeof(SimpleTreeComboBox), new FrameworkPropertyMetadata(null, 
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedValueChanged));

        public SimpleTreeComboBox()
        {
            InitializeComponent();
            this.Loaded += SimpleTreeComboBox_Loaded;
        }

        private void SimpleTreeComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("SimpleTreeComboBox_Loaded called");
            System.Diagnostics.Debug.WriteLine($"DataContext type: {DataContext?.GetType().Name}");
            
            // 延迟更新，确保数据绑定完成
            Dispatcher.BeginInvoke(new System.Action(() =>
            {
                System.Diagnostics.Debug.WriteLine($"Delayed update - ItemsSource count: {ItemsSource?.Count ?? 0}");
                UpdateItems();
            }), System.Windows.Threading.DispatcherPriority.Loaded);
        }

        public ObservableCollection<MaterialCategory> ItemsSource
        {
            get { return (ObservableCollection<MaterialCategory>)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public string SelectedValue
        {
            get { return (string)GetValue(SelectedValueProperty); }
            set { SetValue(SelectedValueProperty, value); }
        }

        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is SimpleTreeComboBox control)
            {
                control.UpdateItems();
            }
        }

        private static void OnSelectedValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is SimpleTreeComboBox control)
            {
                control.CategoryComboBox.SelectedValue = control.SelectedValue;
            }
        }

        private void UpdateItems()
        {
            System.Diagnostics.Debug.WriteLine($"SimpleTreeComboBox.UpdateItems called, ItemsSource count: {ItemsSource?.Count ?? 0}");
            
            if (ItemsSource == null || ItemsSource.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine("ItemsSource is null or empty, clearing ComboBox");
                CategoryComboBox.ItemsSource = null;
                return;
            }

            try
            {
                var flatItems = FlattenCategories(ItemsSource.ToList());
                System.Diagnostics.Debug.WriteLine($"Flattened {flatItems.Count} items");
                
                // 先清空再设置，确保UI更新
                CategoryComboBox.ItemsSource = null;
                CategoryComboBox.ItemsSource = flatItems;
                CategoryComboBox.SelectedValuePath = "Id";
                
                // 移除旧的事件处理器，添加新的
                CategoryComboBox.SelectionChanged -= CategoryComboBox_SelectionChanged;
                CategoryComboBox.SelectionChanged += CategoryComboBox_SelectionChanged;
                
                // 如果有选中值，重新设置
                if (!string.IsNullOrEmpty(SelectedValue))
                {
                    CategoryComboBox.SelectedValue = SelectedValue;
                }
                
                System.Diagnostics.Debug.WriteLine("SimpleTreeComboBox items updated successfully");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error in UpdateItems: {ex.Message}");
            }
        }

        private void CategoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CategoryComboBox.SelectedValue != null)
            {
                SelectedValue = CategoryComboBox.SelectedValue.ToString();
            }
        }

        private List<MaterialCategory> FlattenCategories(List<MaterialCategory> categories, int level = 0)
        {
            var result = new List<MaterialCategory>();
            
            foreach (var category in categories)
            {
                // 确保层级正确设置
                category.Level = level;
                result.Add(category);
                
                System.Diagnostics.Debug.WriteLine($"Flattening: {category.CategoryName} (Level: {category.Level})");
                
                if (category.Children != null && category.Children.Count > 0)
                {
                    result.AddRange(FlattenCategories(category.Children, level + 1));
                }
            }
            
            return result;
        }
    }

    /// <summary>
    /// 层级到宽度转换器
    /// </summary>
    public class LevelToWidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int level)
            {
                return level * 20.0;
            }
            return 0.0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}